import { Project, SearchRet } from '../../../shared/model/defination';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { SortType, ProjectSearchCriteria } from '../../../entities/entities';
import { AuthService } from '../../../services/auth-service';
// import { SearchRet } from '../../../services/core/base-generic-service';
import { ProjectService } from '../../../services/project-service';
import { Router } from '@angular/router';
import { MdlDialogService, MdlSnackbarService } from '@angular-mdl/core';

@Component({
  selector: 'app-project-index',
  templateUrl: './project-index.component.html',
  styleUrls: ['./project-index.component.scss'],
  providers: [AuthService, ProjectService, MdlDialogService, MdlSnackbarService]
})
export class ProjectIndexComponent implements OnInit {
  constructor(
    private _projectService: ProjectService,
    private _authService: AuthService,
    private _router: Router,
    private _dialogService: MdlDialogService,
    private _snackBarService: MdlSnackbarService
  ) {}
  // @ViewChild('confirmAlert')
  // public confirmAlert;
  public count: number = 0;
  public offset: number = 0;
  public limit: number = 10;
  public deleteId: number = 0;
  public isPageLoading: boolean = false;
  public rows = [];
  public pagerMessage = {
    emptyMessage: '没有数据',
    totalMessage: '总计'
  };
  public columns = [
    { name: 'Id', prop: 'id' },
    { name: '项目名称', prop: 'projectName' },
    { name: '所属城市', prop: 'city' },
    { name: '所属省份', prop: 'province' },
    { name: '所属辖区', prop: 'district' }
  ];
  async ngOnInit() {
    this.page(this.offset, this.limit);
  }
  async page(offset, limit) {
    this.isPageLoading = true;
    // let criteria: ProjectSearchCriteria = ProjectSearchCriteria.fromJS({
    // 	PageSize: this.limit,
    // 	PageNumber: offset + 1,
    // 	SortBy: 'Id',
    // 	SortType: SortType[SortType.Descending],
    // 	IsDeleted: false
    // });
    let criteria: any = {};
    try {
      let action$ = <Observable<SearchRet<Project>>>this._projectService.Search(
        criteria
      );
      let searchRet: any = await action$.toPromise();
      this.count = searchRet.totalPageRecords;

      const start = offset * limit;
      const end = start + limit;
      const rows = [...this.rows];

      for (let i = start; i < end; i++) {
        rows[i] = searchRet.items[i - start];
      }

      this.rows = rows;
      this.isPageLoading = false;
      console.log('Page Results', start, end, rows);
    } catch (e) {
      if (e.status === 401) {
        this._router.navigate(['/login']);
      }
    } finally {
      this.isPageLoading = false;
    }
  }

  fetch(cb) {
    const req = new XMLHttpRequest();
    req.open('GET', `assets/projects.json`);

    req.onload = () => {
      cb(JSON.parse(req.response));
    };

    req.send();
  }

  async delete(id) {
    try {
      await this._dialogService
        .confirm('确定删除此项目？', '取消', '确认')
        .toPromise();
      await this._projectService.Delete(+id).toPromise();
      await this.ngOnInit();
    } catch (e) {
      this._snackBarService.showToast(e.message);
    } finally {
    }
  }

  onPage(event) {
    console.log('Page Event', event);
    this.page(event.offset, event.limit);
  }
}
